package top.yeyusmile.service;

import com.google.gson.Gson;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import top.yeyusmile.common.MyTemplate;
import top.yeyusmile.pojo.KuWoSearchResult;
import top.yeyusmile.pojo.MyQQMessage;
import top.yeyusmile.utils.HttpUtil;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @author 夜雨
 * @Web www.yeyusmile.top
 * @date 2022/3/15 23:41
 */

@Service
public class DianGeServiceImpl implements DianGeService {

    @Autowired
    private final MyTemplate myTemplate;

    //private MyQQMessage myQQMessage;

    // private KuWoSearchResult result;


    public DianGeServiceImpl(MyTemplate myTemplate) {
        this.myTemplate = myTemplate;
    }

    @Override
    public void diange(MyQQMessage message) {
        //this.myQQMessage = message;

        try {
            message.setMqMsg(URLDecoder.decode(message.getMqMsg(), "utf-8"));

            String url = "http://search.kuwo.cn/r.s?all=" + URLEncoder.encode(message.getMqMsg().replaceAll("点歌", ""), "utf-8") + "&ft=music&itemset=web_2013&client=kt&pn=0&rn=1&rformat=json&encoding=utf8";


            HttpUtil.sendOkHttpRequest(url, new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {

                    System.out.println(e);
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    KuWoSearchResult result = new Gson().fromJson(response.body().string(),
                            KuWoSearchResult.class);
                    System.out.println(result);
                    //System.out.println(response.body().string());
                    getMp3(result, message);

                }
            });


           /* try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }*/

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }

    /**
     * 解析mp3地址
     *
     * @param result
     */
    private void getMp3(KuWoSearchResult result, MyQQMessage message) {

        //this.result = result;

        if (result != null && result.getList() != null) {
            String musicId = result.getList().get(0).getMusicId();
            String artist = result.getList().get(0).getArtist();
            String name = result.getList().get(0).getName();
            try {

                String url = "http://antiserver.kuwo.cn/anti.s?response=url&rid=" + musicId + "&format=mp3&type=convert_url";

                HttpUtil.sendOkHttpRequest(url, new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {

                        System.out.println(e);
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        //System.out.println(response.body().string());
                        sendXml(response.body().string(), artist, name, message);//发送xml音乐卡片消息
                    }
                });


               /* try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }*/

            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    }

    /**
     * 发送xml音乐卡片消息
     *
     * @param mp3url 音乐地址
     * @param artist 作者
     * @param name   歌名
     */
    private void sendXml(String mp3url, String artist, String name,MyQQMessage myQQMessage) {
        String xmlMsg = String.format("<?xml version='1.0' encoding='UTF-8' standalone='yes' ?><msg serviceID=\"2\" templateID=\"1\" action=\"web\" brief=\"Music\" sourceMsgId=\"0\" url=\"\" flag=\"0\" adverSign=\"0\" multiMsgFlag=\"0\"><item layout=\"2\"><audio cover=\"\" src=\"%s\" /><title>%s</title><summary>%s</summary></item><source name=\"\" icon=\"\" action=\"\" appid=\"-1\" /></msg>", mp3url, name, artist);
        Map<String, Object> params = new LinkedHashMap<>();
        params.put("c1", myQQMessage.getMqRobot());
        params.put("c2", 0);
        params.put("c3", myQQMessage.getMqType());
        params.put("c4", myQQMessage.getMqFromid());
        params.put("c5", myQQMessage.getMqFromqq());
        params.put("c6", xmlMsg);
        myTemplate.sendXml(params);

    }
}
